<template>
  <view>
    <view class="handler-bar" v-if="childService">
      <view class="title" @click="changeChildTab">
        {{childService.label||''}}
      </view>
      <view class="handler">
        <button class="cu-btn border line-blue sm" v-show="disabled!==true||btn.button_type=='refresh'"
          v-for="btn in gridButtonsRun" @click.stop="onButton(btn)">{{btn.button_name||''}}</button>
        <button class="cu-btn border line-blue sm" v-if="setList.length===5&&loadStatus==='more'"
          @click.stop="onButton({button_type:'list'})">全部</button>
      </view>
    </view>
    <child-list-item :config="setConfig" :detail="item" :labels="setLabels" :rowButton="rowButtonsRun"
      @click-list-item="clickItem" @click-foot-btn="clickFootBtn($event,index)" v-for="(item,index) in setList"
      ref="childList" v-show="item._dirtyFlags!=='delete'">
    </child-list-item>
    <child-list-item :config="setConfig" :detail="item" :labels="setLabels" :rowButton="rowButtonsRun"
      @click-list-item="clickItem" @click-foot-btn="clickFootBtn($event,index)" v-for="(item,index) in memoryListData">
    </child-list-item>
    <view class="no-data" v-if="loadStatus==='noMore'&&setList.length==0&&memoryListData.length===0">
      暂无数据
    </view>
    <!-- 子表增加表单 -->
    <view class="cu-modal" @click.stop="hideModal" :class="{show:modalName==='addChildData'}">
      <view class="cu-dialog bg-white" @click.stop.prevent="">
        <view class="modal-content">
          <view class="title-bar" v-if="addV2">
            <view class=""></view>
            <view class="title">
              {{addV2.service_view_name||''}}
            </view>
            <button class="cu-btn bg-white shadow-blur" @click="hideModal"><text class="cuIcon-close"></text></button>
          </view>
          <view class="close-btn text-right">
          </view>
          <view class="child-form-wrap" v-if="addV2&&modalName==='addChildData'">
            <bx-form :srvApp="appName||destApp" v-if="addV2 && addV2._fieldInfo && isArray(addV2._fieldInfo)"
              :fields="addV2._fieldInfo" :pageType="use_type" :mainData="mainData" :formType="'add'" ref="childForm"
              :key="modalName" @value-blur="valueChange" />
          </view>
          <view class="button-box" v-if="addV2&&modalName==='addChildData'&&addV2.formButton">
            <button class="cu-btn bg-blue" v-for="btn in addV2.formButton"
              @click="onChildFormBtn(btn)">{{btn.button_name||''}}</button>
          </view>
        </view>
      </view>
    </view>
    <!-- 子表编辑表单 -->
    <view class="cu-modal" @click.stop="hideModal" :class="{show:modalName==='updateChildData'}">
      <view class="cu-dialog" @click.stop.prevent="">
        <view class="close-btn text-right">
          <button class="cu-btn bg-white shadow-blur" @click="hideModal()"><text class="cuIcon-close"></text></button>
        </view>
        <view class="child-form-wrap" v-if="updateV2&&modalName==='updateChildData'">
          <bx-form v-if="updateV2 && updateV2._fieldInfo && isArray(updateV2._fieldInfo)" :fields="updateV2._fieldInfo"
            :main-data="mainData" :pageType="use_type" :formType="'update'" ref="childForm" :key="modalName" />
        </view>
        <view class="button-box" v-if="updateV2&&modalName==='updateChildData'&&updateV2.formButton">
          <button class="cu-btn bg-blue" v-for="btn in updateV2.formButton"
            @click="onChildFormBtn(btn)">{{btn.button_name||''}}</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
  export default {
    name: "child-list",
    data() {
      return {
        serviceName: "",
        colsV2Data: null,
        oldAddV2: null,
        addV2: null,
        oldUpdateV2: null,
        updateV2: null,
        pageNo: 1,
        listData: [],
        localListData: [],
        fields: [],
        loadStatus: "more",
        modalName: null,
        memoryListData: [],
        selectColInfo: null,
        currentItemIndex: null,
        currentItemType: "",
      };
    },
    methods: {
      changeChildTab() {
        this.$emit('changeTab')
      },
      /**
       * 生成主子表同时提交的子表请求参数
       */
      getChildDataList() {
        const fk = this.foreignKey
        const depend_keys = [{
          type: "column",
          depend_key: fk.referenced_column_name,
          add_col: fk.column_name
        }]
        let result = [];
        const deleteParams = this.buildDeleteParams()
        // deleteParams && result.push(deleteParams)
        const addParams = this.buildAddParams()
        // addParams && result.push(addParams)
        const updateParams = this.buildUpdateParams()
        result = [...result, ...deleteParams, ...addParams, ...updateParams]
        result = result.map(item => {
          item.depend_keys = depend_keys
          return item
        })
        debugger
        return result
      },
      buildDeleteParams() {
        let fk = this.foreignKey
        let deleteList = this.listData.filter(item => item._dirtyFlags === 'delete')
        if (deleteList.length === 0) {
          return []
        }
        let ids = deleteList.map(row => row.id).join(",");
        let params = {
          condition: [{
            colName: 'id',
            ruleType: 'in',
            value: ids
          }],
          serviceName: this.deleteService
        }
        return [params]
      },
      buildUpdateParams() {
        let fk = this.foreignKey
        let updateList = this.finalListData.filter(item => item._dirtyFlags === 'update' && item.id)
        if (updateList.length === 0) {
          return []
        }
        updateList = this.deepClone(updateList)
        let params = updateList.map((item, index) => {
          delete item._isMemoryData
          delete item._dirtyFlags
          let row = this.localListData[index]
          let id = item.id
          Object.keys(row).forEach(key => {
            if (row[key] === item[key]) {
              delete item[key]
            }
          })
          return {
            serviceName: this.updateService,
            data: [item],
            condition: [{
              colName: "id",
              ruleType: "eq",
              value: id,
            }]
          }
        })
        return params
      },
      buildAddParams() {
        let fk = this.foreignKey
        let addList = this.finalListData.filter(item => item._dirtyFlags === 'add')
        if (addList.length === 0) {
          return []
        }
        addList = this.deepClone(addList)
        let params = {
          data: addList.map(item => {
            delete item._isMemoryData
            delete item._dirtyFlags
            return item
          }),
          serviceName: this.addService
        }
        return [params]
      },
      async add2List(e) {
        let data = this.$refs.childForm.getFieldModel();
        if (!data) {
          return
        }
        data = this.deepClone(data)
        if (typeof data === 'object' && Object.keys(data).length > 0) {
          for (let key in data) {
            if (Array.isArray(data[key])) {
              data[key] = data[key].toString();
            }
            if (!data[key] && data[key] !== 0) {
              delete data[key]
            }
          }
          if (this.use_type === 'detaillist') {
            // 直接添加
            let reqData = [{
              serviceName: e.service_name,
              data: [data]
            }];

            let app = this.appName || uni.getStorageSync('activeApp');
            let type = "add"
            let url = this.getServiceUrl(app, e.service_name, type);
            let res = await this.$http.post(url, reqData);

            this.getList()
            if (res.data.state === 'SUCCESS') {
              uni.showModal({
                title: '提示',
                content: res.data.resultMessage,
                showCancel: false
              })
            } else {
              uni.showToast({
                title: res.data.resultMessage,
                mask: false,
                icon: "none"
              });
            }
            // this.$emit('addChild',{row:data,btn:e})
          } else {
            // 添加到内存中，随主表一起添加
            if (Object.keys(data).length > 0) {
              data._isMemoryData = true
              data._dirtyFlags = 'add'
              this.memoryListData.push(data)
            }
          }

        }

        this.addV2._fieldInfo = this.addV2._fieldInfo.map(item => {
          item.value = null
          if (item.defaultValue && !item.value) {
            item.value = item.defaultValue
          }
          if (item.in_add === 1) {
            item.display = true
          }
          if (item.column === this.foreignKey?.referenced_column_name) {
            item.display = false
          }
          return item
        })
        this.$emit('change', {
          data: this.finalListData,
          info: this.childService.foreign_key
        }, )
        this.modalName = ''
      },
      deleteMemoryListItem(index) {
        if (index || index === 0) {
          this.memoryListData.splice(index, 1)
        }
        this.$emit('change', {
          data: this.finalListData,
          info: this.childService.foreign_key
        }, )
      },
      updateChildListItem() {
        let data = this.$refs.childForm.getFieldModel();
        if (!data) {
          return
        }
        if (this.use_type === 'detaillist') {
          // 详情子表页面 直接发请求修改
          let id = this.listData[this.currentItemIndex]['id']
          if (id && this.updateService) {
            let req = [{
              "serviceName": this.updateService,
              "condition": [{
                "colName": 'id',
                "ruleType": "eq",
                "value": id
              }],
              "data": [data]
            }]
            let app = this.appName || uni.getStorageSync('activeApp');
            let url = this.getServiceUrl(app, this.updateService, 'update');
            this.$http.post(url, req).then(res => {
              uni.showModal({
                title: "提示",
                content: res.data.resultMessage,
                showCancel: false,
                confirmText: '知道了'
              })
              this.hideModal()
              this.getList()
            })
          }
          return
        }

        if (this.currentItemType === 'mem') {
          Object.assign(this.memoryListData[this.currentItemIndex], data)
          this.memoryListData[this.currentItemIndex]._dirtyFlags = 'add'
        } else {
          Object.assign(this.listData[this.currentItemIndex], data)
          this.listData[this.currentItemIndex]._dirtyFlags = 'update'
        }
        this.$emit('change', {
          data: this.finalListData,
          info: this.childService.foreign_key
        }, )
        this.hideModal()
      },
      onChildFormBtn(e, index, isMem) {
        if (e && e.button_type) {
          switch (e.button_type) {
            case 'submit':
              this.add2List(e)
              break;
            case 'edit':
              this.updateChildListItem(index)
              break;
            case 'delete':
              if (this.use_type === "detaillist" && this.modalName === "updateChildData") {
                let id = this.listData[this.currentItemIndex]['id']
                uni.showModal({
                  content: "是否确认删除操作？",
                  success: (res) => {
                    if (res.confirm) {
                      console.log('用户点击确定');
                      let req = [{
                        "serviceName": e.service_name,
                        "colNames": ["*"],
                        "condition": [{
                          colName: 'id',
                          ruleType: 'eq',
                          value: id
                        }]
                      }]
                      if (!id) {
                        return
                      }
                      let appName = this.appName || uni.getStorageSync('activeApp');
                      this.onRequest("delete", e.service_name,
                        req, appName).then((res) => {
                        this.hideModal()
                        this.getList()
                        if (res.data.state === "SUCCESS") {
                          uni.showToast({
                            title: '操作成功',

                          })

                        } else {
                          uni.showModal({
                            title: '提示',
                            content: res.data
                              .resultMessage,
                            showCancel: false,
                          })
                        }
                      })

                    } else if (res.cancel) {
                      resolve('用户点击取消')
                    }
                  }
                })
                return
              }
              if (typeof index === 'number' && index >= 0) {
                if (isMem) {
                  this.deleteMemoryListItem(index)
                } else {
                  this.listData[index]._dirtyFlags = 'delete'
                  this.$set(this.listData, index, this.listData[index])
                  this.$emit('change', {
                    data: this.finalListData,
                    info: this.childService.foreign_key
                  }, )
                }
              }
              break;
            case 'reset':
              this.$refs.childForm.onReset()
              break;
          }
        }
      },
      async valueChange(e, triggerField) {
        const column = triggerField.column
        const fieldModel = e
        const cols = this.addV2._fieldInfo.filter(item => item.x_if).map(item => item.column)
        const table_name = this.addV2.main_table

        let result = null
        if (Array.isArray(cols) && cols.length > 0) {
          // #ifdef MP-WEIXIN
          result = await this.evalX_IF(table_name, cols, fieldModel, this.appName)
          // #endif
        }
        for (let i = 0; i < this.addV2._fieldInfo.length; i++) {
          const item = this.addV2._fieldInfo[i]
          if (item.x_if) {
            if (Array.isArray(item.xif_trigger_col) && item.xif_trigger_col.includes(column)) {
              if (item.table_name !== table_name) {
                // #ifdef MP-WEIXIN
                result = await this.evalX_IF(item.table_name, [item.column], fieldModel, this.appName)
                // #endif
              }
              if (result?.response && result.response[item.column]) {
                item.display = true
              } else if (result === true) {
                item.display = true
              } else {
                item.display = true
                // item.display = false
              }
            }
          }
          if (e && typeof e === 'object' && e.hasOwnProperty(item.column)) {
            item.value = e[item.column];
          }
          this.$set(this.addV2._fieldInfo, i, item)
        }
      },
      async onButton(e, index) {
        if (e && e.button_type) {
          switch (e.button_type) {
            case 'refresh':
              this.getList()
              break;
            case 'list':
              let url =
                `/publicPages/list/list?pageType=list&main_data=${JSON.stringify(this.mainData)}&serviceName=${this.serviceName}&destApp=${this.srvApp}&cond=${JSON.stringify(this.condition)}`
              if (this.disabled === true) {
                url = +'&disabled=true'
              }
              uni.navigateTo({
                url
              })
              break;
            case 'add':
              this.getAddV2(e)
              this.modalName = 'addChildData'
              break;
            case 'edit':
              if (index || index === 0) {
                let row = this.listData[index]
                this.getUpdateV2(row)
                this.currentItemIndex = index
                this.modalName = 'updateChildData'
              }
              break;
            case 'editMem':
              // 编辑内存表数据
              if (index || index === 0) {
                let row = this.memoryListData[index]
                this.getUpdateV2(row)
                this.currentItemIndex = index
                this.currentItemType = 'mem'
                this.modalName = 'updateChildData'
              }
              break
            case 'batchAdd':
              let addV2 = await this.getAddV2();
              this.$refs.batchAdd.open(e)
              break;
          }
        }
      },
      clickItem(data) {
        this.$emit('click-list-item', data);
      },

      async clickFootBtn(data, index) {
        debugger
        let buttonInfo = this.deepClone(data.button);
        let rowData = this.deepClone(data.row);
        if (rowData._isMemoryData === true) {
          if (buttonInfo.button_type === 'delete') {
            this.memoryListData.splice(index, 1)
          } else if (buttonInfo.button_type === 'edit') {
            if (index || index === 0) {
              let row = this.memoryListData[index]
              this.getUpdateV2(row)
              this.currentItemIndex = index
              this.currentItemType = 'mem'
              this.modalName = 'updateChildData'
            }
            return
          }
          return
        }
        if (this.type === 'detaillist') {
          if (buttonInfo.button_type === 'delete') {
            // rowData._dirtyFlags = 'delete'
            // this.$set(this.listData, index, rowData)
            // return
          } else if (buttonInfo.button_type === 'edit') {
            if (index || index === 0) {
              let row = this.listData[index]
              this.getUpdateV2(row)
              this.currentItemIndex = index
              this.modalName = 'updateChildData'
            }
            return
          } else if (buttonInfo.button_type === 'editMem') {
            if (index || index === 0) {
              let row = this.memoryListData[index]
              this.getUpdateV2(row)
              this.currentItemIndex = index
              this.currentItemType = 'mem'
              this.modalName = 'updateChildData'
            }
            return
          }
        }
        if (buttonInfo.operate_params && typeof buttonInfo.operate_params === 'string') {
          try {
            buttonInfo.operate_params = JSON.parse(buttonInfo.operate_params);
            if (Array.isArray(buttonInfo.operate_params.condition) && buttonInfo.operate_params.condition
              .length > 0) {
              buttonInfo.operate_params.condition.forEach(cond => {
                if (typeof cond.value === 'object' && cond.value.value_type === 'rowData') {
                  cond.value = data.row[cond.value.value_key];
                } else if (typeof cond.value === 'object' && cond.value.value_type ===
                  'constant') {
                  cond.value = cond.value.value;
                }
              });
            }
            if (buttonInfo && buttonInfo.operate_params && buttonInfo.operate_params.data && Array.isArray(
                buttonInfo.operate_params.data) && buttonInfo.operate_params.data.length >
              0) {
              buttonInfo.operate_params.data.forEach(data => {
                if (typeof data === 'object') {
                  Object.keys(data).forEach(item => {
                    if (typeof data[item] === 'object' && data[item].value_type ===
                      'rowData') {
                      data[item] = rowData[data[item].value_key];
                    } else if (typeof data[item] === 'object' && data[item]
                      .value_type === 'constant') {
                      data[item] = data[item].value;
                    }
                  });
                }
              });
            }
            if (buttonInfo.operate_type === '操作' && buttonInfo.operate_mode === '静默操作') {
              let req = [{
                serviceName: buttonInfo.operate_service,
                condition: buttonInfo.operate_params.condition,
                data: buttonInfo.operate_params.data
              }];
              let app = this.destApp || this.appName || uni.getStorageSync('activeApp');
              let url = this.getServiceUrl(buttonInfo.application ? buttonInfo.application : app,
                buttonInfo.operate_service, buttonInfo.servcie_type);
              let res = await this.$http.post(url, req);
              if (res.data.state === 'SUCCESS') {
                // this.$refs.bxList.onRefresh();
                this.getList()
              }
            } else if (buttonInfo.operate_type === '更新弹出') {
              let params = {
                type: buttonInfo.servcie_type,
                serviceName: buttonInfo.operate_service,
                main_table: buttonInfo.main_table,
                service: buttonInfo.service,
                button_type: buttonInfo.button_type,
              };
              if (Array.isArray(buttonInfo.operate_params.data) && buttonInfo.operate_params.data
                .length > 0) {
                params.defaultVal = buttonInfo.operate_params.data[0]
              }
              uni.navigateTo({
                url: '/pages/public/formPage/formPage?serviceName=' +
                  buttonInfo.operate_service +
                  '&type=' +
                  buttonInfo.servcie_type +
                  '&params=' + JSON.stringify(params) +
                  '&cond=' +
                  decodeURIComponent(JSON.stringify(buttonInfo.operate_params.condition))
              });
            }
          } catch (e) {
            console.error(e);
            //TODO handle the exception
          }
        }

        if (this.pageType === 'proc') {
          if (data.button && data.button.button_type === 'edit' && data.row.proc_instance_no) {
            uni.navigateTo({
              url: '/pages/public/proc/procDetail/procDetail?proc_instance_no=' + data.row
                .proc_instance_no
            });
          }
        } else {
          this.onButtonToUrl(data).then(res => {
            if (data.button && data.button.button_type === 'delete') {
              if (res.state === 'SUCCESS') {
                this.getList()
                // this.$refs.childList.onRefresh();
              } else {
                uni.showToast({
                  title: res.resultMessage,
                  icon: 'none'
                })
              }
            }
            if (data.button && data.button.button_type === 'detail') {
              let row = res.row;
              let btn = res.button;
              let params = {
                type: 'detail',
                condition: [{
                  colName: 'id',
                  ruleType: 'in',
                  value: row.id
                }],
                serviceName: btn.service_name,
                // defaultVal: row
              };
              uni.navigateTo({
                url: `/pages/public/formPage/formPage?destApp=${this.destApp}&params=` +
                  JSON.stringify(params)
              });
            } else if (data.button && (data.button.button_type === 'duplicate' || data.button
                .button_type === 'duplicatedeep')) {
              let fieldsCond = []
              if (Array.isArray(self.condition)) {
                self.condition.forEach(item => {
                  fieldsCond.push({
                    column: item.colName,
                    value: item.value,
                    display: false
                  })
                })
              }

              let params = {
                type: 'add',
                serviceName: res.button.service_name,
                defaultVal: res.row,
                eventOrigin: res.button
              };

              Object.keys(params.defaultVal).forEach(key => {
                if (['id', 'modify_user_disp', 'modify_user', 'modify_time',
                    'create_user_disp', 'create_user', 'create_time'
                  ].includes(key) || !params.defaultVal[key]) {
                  delete params.defaultVal[key]
                }
              })

              uni.navigateTo({
                url: `/pages/public/formPage/formPage?destApp=${this.destApp}&params=${JSON.stringify(params)}`
              });

            } else if (data.button.servcie_type === 'select') {
              let params = {
                type: 'select',
                serviceName: res.button.service_name,
                defaultVal: res.row,
                eventOrigin: res.button
              };
            } else if (data.button.servcie_type === 'add') {
              let params = {
                type: 'add',
                serviceName: res.button.service_name,
                defaultVal: res.row,
                eventOrigin: res.button
              };
              uni.navigateTo({
                url: '/pages/public/formPage/formPage?params=' + JSON.stringify(params)
              });
            } else if (data.button && data.button.operate_type === '流程申请') {
              uni.navigateTo({
                url: '/pages/public/proc/apply/apply?serviceName=' + data.button
                  .operate_service
              });
            } else if (data.button && data.button.button_type === 'customize') {
              let moreConfig = data.button.more_config;
              console.log(buttonInfo, rowData)
              if (moreConfig && typeof moreConfig === 'string') {
                try {
                  moreConfig = JSON.parse(moreConfig);
                } catch (e) {
                  //TODO handle the exception
                  console.log(e);
                }
              }
              debugger
              if (data.button?.button_name === '支付码') {
                // 跳转到下单、生成支付码页面
                uni.navigateTo({
                  url: `/pages/public/payCode/payCode?id=${data.row.id}`
                })
                return
              } else if (data.button?.button_name === '填写问卷') {
                uni.navigateTo({
                  url: `/pages/specific/quest/quest?id=${data.row.id}`
                })
                return
              }
              let params = {
                type: buttonInfo.servcie_type == 'operate' ? 'update' : buttonInfo
                  .servcie_type,
                serviceName: buttonInfo.operate_service,
                main_table: buttonInfo.main_table,
                service: buttonInfo.service,
                button_type: buttonInfo.button_type == 'operate' ? 'update' : buttonInfo
                  .button_type,
              };
              if (buttonInfo && buttonInfo.operate_params && buttonInfo.operate_params.data &&
                Array.isArray(buttonInfo.operate_params.data) && buttonInfo.operate_params.data
                .length > 0) {
                params.defaultVal = buttonInfo.operate_params.data[0]
              }
              if (buttonInfo && buttonInfo.operate_params && buttonInfo.operate_params
                .condition &&
                Array.isArray(buttonInfo.operate_params.condition) && buttonInfo.operate_params
                .condition
                .length > 0) {
                params.condition = buttonInfo.operate_params.condition
              }
              let url = ''
              switch (buttonInfo.servcie_type) {
                case 'add':
                case 'operate':
                  params.service = buttonInfo.operate_service
                  url =
                    `/pages/public/formPage/formPage?params=${JSON.stringify(params)}&destApp=${this.destApp}`
                  break;
              }
              switch (buttonInfo.operate_type) {
                case '详情跳转':
                  params.type = 'detail'
                  url =
                    `/pages/public/formPage/formPage?params=${JSON.stringify(params)}&destApp=${this.destApp}`
                  break;
                case '列表弹出':
                  let cond = buttonInfo.operate_params.condition
                  if (Array.isArray(cond)) {
                    url =
                      `/pages/public/list/list?pageType=list&serviceName=${buttonInfo.operate_service}&cond=${JSON.stringify(cond)}&destApp=${this.destApp}`
                  }
                  break;
                case 'URL跳转':
                  if (buttonInfo.pre_data_handle) {
                    // #ifdef H5
                    let arr = []
                    arr.push(rowData)
                    let result = eval("var fun=" + buttonInfo.pre_data_handle +
                      "(arr); fun")
                    if (result) {
                      let url = result.slice(result.indexOf('/pages/'))
                      uni.navigateTo({
                        url,
                        fail: () => {
                          window.location.href = result
                        }
                      })
                    }
                    // #endif
                  }

                  return
                case 'operate':

                  break;
              }
              if (params && url) {
                debugger
                uni.navigateTo({
                  url
                })
              }
            }
          });
        }
        console.log('clickFootBtn:', data);
      },
      async getList() {
        let childService = this.deepClone(this.childService)
        if (childService?.foreign_key?.column_name && this.mainData && childService?.foreign_key
          ?.referenced_column_name && this.mainData[childService?.foreign_key?.referenced_column_name]) {
          let app = this.appName || uni.getStorageSync('activeApp');
          let url = this.getServiceUrl(app, this.serviceName, 'select');
          let req = {
            "serviceName": this.serviceName,
            "colNames": ["*"],
            "condition": [{
              "colName": childService.foreign_key.column_name,
              "ruleType": "eq",
              "value": this.mainData[childService.foreign_key.referenced_column_name]
            }],
            "relation_condition": {},
            "page": {
              "pageNo": this.pageNo,
              "rownumber": 5
            },
          }
          let res = await this.$http.post(url, req)
          if (res.data.state === 'SUCCESS') {
            this.listData = res.data.data
            this.localListData = this.deepClone(res.data.data)
            if (res.data.page.total <= res.data.page.rownumber * res.data.page.pageNo) {
              this.loadStatus = 'noMore'
            } else {
              this.loadStatus = 'more'
            }
            this.$emit('change', {
              data: this.finalListData,
              info: this.childService.foreign_key
            }, )
          }
        }
      },
      async getUpdateV2(row) {
        if (this.updateV2?._fieldInfo) {
          this.updateV2._fieldInfo = this.updateV2._fieldInfo.map(item => {
            if (row && row[item.column]) {
              item.value = row[item.column]
            }
            return item
          })
          this.updateV2.rowData = row
          return
        }
        let app = this.appName || uni.getStorageSync('activeApp');
        let colVs = await this.getServiceV2(this.updateService, 'update', 'update', app);
        debugger
        colVs._fieldInfo = colVs._fieldInfo.map(item => {
          if (Array.isArray(item?.option_list_v2?.conditions) && item.option_list_v2
            .conditions
            .length > 0) {
            item.option_list_v2.conditions = this.evalConditions(item.option_list_v2
              .conditions, this.mainData)
          }
          if (item.defaultValue) {
            item.value = item.defaultValue
          }
          if (item.in_update === 1) {
            item.display = true
          }
          if (item.column === this.foreignKey?.ref_service_column) {
            item.display = false
          }
          if (item.column === this.foreignKey?.referenced_column_name) {
            item.display = false
          }
          if (row && row[item.column]) {
            item.value = row[item.column]
          }
          return item
        })
        debugger
        colVs.rowData = row
        if (Array.isArray(colVs.formButton) && colVs.formButton.length > 0 && this.use_type === "detaillist") {
          colVs.formButton = colVs.formButton.map(item => {
            if (item.button_type === 'reset') {
              let rowButton = this.v2Data?.rowButton
              if (rowButton && rowButton.length > 0) {
                let delBtn = rowButton.find(item => item.button_type === 'delete')
                if (delBtn) {
                  item = delBtn
                }
              }
            }
            return item
          })
        }
        colVs.formButton = colVs.formButton.filter(item => {
          return !['reset'].includes(item.button_type)
        })
        this.oldUpdateV2 = this.deepClone(colVs)
        this.updateV2 = colVs
      },
      async getAddV2(btn) {
        // 
        let serviceName = btn?.service_name || this.serviceName
        let app = this.appName || uni.getStorageSync('activeApp');
        let colVs = null

        if (this.oldAddV2) {
          colVs = this.deepClone(this.oldAddV2)
          this.addV2 = null
          colVs._fieldInfo = colVs._fieldInfo.map(item => {
            item.value = ''
            return item
          })
        } else {
          colVs = await this.getServiceV2(serviceName, 'add', 'add', app);
        }
        if (!colVs) {
          return
        }
        colVs.formButton = colVs.formButton.filter(item => {
          return !['reset'].includes(item.button_type)
        })
        colVs._fieldInfo = colVs._fieldInfo.map(item => {
          item.value = ''
          if (Array.isArray(item?.option_list_v2?.conditions) && item.option_list_v2.conditions
            .length > 0) {
            item.option_list_v2.conditions = this.evalConditions(item.option_list_v2.conditions,
              this.mainData)
          }
          if (item.defaultValue) {
            item.value = item.defaultValue
          }
          if (item.in_add === 1) {
            item.display = true
          } else {
            item.display = false
          }
          if (item.column === this.foreignKey?.referenced_column_name) {
            item.display = false
          }
          let self = this
          if (this.mainTable && item.col_type == this.mainTable) {
            item.display = false
            if (this.mainData && this.mainData[item.column]) {
              item.value = this.mainData[item.column]
              item.disabled = true
            }
          }
          if (item.col_type === 'fk') {
            if (this.mainData && this.mainData[item.column]) {
              item.value = this.mainData[item.column]
              item.disabled = true
            }
          }
          return item
        })

        let defaultVal = colVs._fieldInfo.reduce((res, cur) => {
          if (cur.value) {
            res[cur.column] = cur.value
          }
          return res
        }, {})
        const cols = colVs._fieldInfo.filter(item => item.x_if).map(item => item.column)
        const table_name = colVs.main_table
        const result = null
        // #ifdef MP-WEIXIN
        await this.evalX_IF(table_name, cols, defaultVal, this.appName)
        // #endif
        // #ifdef H5
        //debugger
        // #endif

        for (let i = 0; i < colVs._fieldInfo.length; i++) {
          const item = colVs._fieldInfo[i]
          if (item.x_if) {
            if (Array.isArray(item.xif_trigger_col)) {
              if (item.table_name !== table_name) {
                // #ifdef MP-WEIXIN
                result = await this.evalX_IF(item.table_name, [item.column], defaultVal, this.appName)
                // #endif
                // #ifdef H5
                debugger
                // #endif
              }
              if (result?.response && result.response[item.column]) {
                item.display = true
              } else if (result === true) {
                item.display = true
              } else {
                debugger
                item.display = true
                // item.display = false
              }
            }
          }
        }

        this.addV2 = colVs
        if (Array.isArray(colVs?._fieldInfo)) {
          let colInfo = null
          let e = this.config?.foreign_key?.moreConfig?.batch_add
          if (e) {
            colInfo = colVs._fieldInfo.find(col => col.column === e.target_column)
            if (Array.isArray(colInfo?.option_list_v2?.conditions) && colInfo.option_list_v2.conditions
              .length > 0) {
              colInfo.option_list_v2.conditions = colInfo.option_list_v2.conditions.map(item => {
                if (item.value && item.value.indexOf('data.') !== -1) {
                  let colName = item.value.slice(item.value.indexOf('data.') + 5);
                  if (this.mainData && this.mainData[colName]) {
                    item.value = this.mainData[colName];
                  }
                } else if (item.value && item.value.indexOf('top.user.user_no') !== -1) {
                  item.value = uni.getStorageSync('login_user_info').user_no;
                } else if (item.value && item.value.indexOf("'") === 0 && item.value
                  .lastIndexOf(
                    "'") === item.value
                  .length - 1) {
                  item.value = item.value.replace(/\'/gi, '');
                }
                if (item.value_exp) {
                  delete item.value_exp;
                }
                return item
              })
            }
            this.selectColInfo = colInfo
          }
        }
        this.oldAddV2 = this.deepClone(colVs)
        return colVs
        // }

      },
      async getColV2() {
        let self = this
        let app = this.appName || uni.getStorageSync('activeApp');
        let colVs = await this.getServiceV2(this.serviceName, 'list', this.use_type || 'detaillist', app);
        this.colsV2Data = colVs;
        if (!colVs) {
          return
        }
        if (colVs.more_config) {
          try {
            let moreConfig = JSON.parse(colVs.more_config)
            colVs.moreConfig = moreConfig
          } catch (e) {
            //TODO handle the exception
          }
        }
        this.fields = this.setFieldsDefaultVal(colVs._fieldInfo, {});
        return this.fields
      },
      buttonIsExps(val, button, type) {
        let mainData = val
        let row = val
        let data = val
        let isShow = true
        if (button.button_type == 'customize') {

        } else if (button.disp_exps) {
          isShow = this.evalBtnDispExps(button.disp_exps, mainData)
          // let testFun = new Function('e', `let mainData = e ; return (${button.disp_exps})`)
          // isShow = testFun(mainData)
        }
        button.visible = isShow ? '是' : '否'
        return button
      },
      showModal(name) {
        this.modalName = name
      },
      hideModal() {
        this.modalName = null
      },
    },
    computed: {
      destApp() {
        return this.appName || uni.getStorageSync('activeApp')
      },
      setList() {
        return this.listData
      },
      setConfig() {
        return this.tempColConfig
      },
      setLabels() {
        if (this.labels) {
          return this.labels
        } else {
          if (Array.isArray(this.colsV2Data?.srv_cols)) {
            return this.colsV2Data.srv_cols.reduce((res, cur) => {
              res[cur.columns] = cur.label
              return res
            }, {})
          }
        }
      },
      use_type() {
        return this.childService.use_type || this.colsV2Data?.use_type || this.type
      },
      foreignKey() {
        return this.childService?.foreign_key
      },
      condition() {
        if (this?.childService?.foreign_key?.column_name && this.mainData[this.childService?.foreign_key
            ?.referenced_column_name]) {
          return [{
            "colName": this.childService.foreign_key.column_name,
            "ruleType": "eq",
            "value": this.mainData[this.childService.foreign_key.referenced_column_name]
          }]
        }
      },
      tempColConfig() {
        if (this.moreConfig?.tempColConfig) {
          return this.moreConfig?.tempColConfig
        } else {
          if (Array.isArray(this.fields)) {
            return {
              title: {},
              cols: this.fields.filter(item => {
                let excludeCol = ['id', 'create_time', 'modify_time', 'create_user', 'modify_user',
                  'create_user_disp', 'modify_time', 'modify_user_disp'
                ]
                if (!excludeCol.includes(item.column) && item.column.indexOf('_no') === -1 && item.column.indexOf(
                    '_disp') === -1) {
                  return true
                }
              }).map(item => {
                let obj = {
                  colName: item.column,
                  showLabel: true
                }
                return obj
              }).slice(0, 5)
            }
          }
        }
      },
      moreConfig() {
        let result = null
        if (this.colsV2Data?.more_config && typeof this.colsV2Data.more_config === 'string') {
          try {
            result = JSON.parse(this.colsV2Data.more_config)
          } catch (e) {}
        }
        return result
      },
      finalListData() {
        return [...this.listData, ...this.memoryListData].filter(item => item._dirtyFlags !== 'delete')
      },
      addService() {
        if (this.serviceName) {
          let index = this.serviceName.lastIndexOf('_')
          return this.serviceName.slice(0, index) + '_add'
        }
      },
      updateService() {
        if (Array.isArray(this.v2Data?.rowButton) && this.v2Data.rowButton.find(item => item.button_type ===
            'edit')) {
          let buttonInfo = this.v2Data.rowButton.find(item => item.button_type === 'edit')
          return buttonInfo?.service_name
        }
        if (this.serviceName) {
          let index = this.serviceName.lastIndexOf('_')
          return this.serviceName.slice(0, index) + '_update'
        }
      },
      deleteService() {
        if (this.serviceName) {
          let index = this.serviceName.lastIndexOf('_')
          return this.serviceName.slice(0, index) + '_delete'
        }
      },
      selectService() {
        if (this.serviceName) {
          let index = this.serviceName.lastIndexOf('_')
          return this.serviceName.slice(0, index) + '_select'
        }
      },
      gridButtonsRun() {
        let res = []
        if (Array.isArray(this.colsV2Data?.gridButton) && this.colsV2Data.gridButton.length > 0) {
          res = this.colsV2Data.gridButton.filter(item => {
            let includeBtn = ['refresh', 'add']
            // let includeBtn = ['refresh','add','batch_delete']
            if (includeBtn.includes(item.button_type)) {
              return true
            }
          })
        }
        return res
      },
      rowButtonsRun: function() {
        let self = this
        let rowButtons = this.colsV2Data?.rowButton || []
        rowButtons = rowButtons.filter((item, index) => {
          if (item.more_config) {
            try {
              item.moreConfig = JSON.parse(item.more_config)
            } catch (e) {
              //TODO handle the exception
            }
          }
          if (this.disabled === true) {
            if (item.button_type !== 'detail') {
              return false
            }
          }
          if (item.permission && item.client_type.indexOf('APP') !== -1) {
            if (item.button_type !== 'undo') {
              if (item.disp_exps) {
                item = this.buttonIsExps(this.mainData, item)
              }
              if (!item.hasOwnProperty('visible')) {
                return item
              } else if (item.hasOwnProperty('visible') && item.visible === '是') {
                return item
              }
            } else if (item.button_type !== 'customize') {}
          }
        })
        return rowButtons
      },
    },
    watch: {
      'childService.service_name': {
        immediate: true,
        handler(newValue, oldValue) {
          if (newValue) {
            this.serviceName = newValue
            this.getColV2().then(_ => {
              this.getList()
            })
          }
        }
      },
      childService: {
        immediate: true,
        deep: true,
        handler(newValue, oldValue) {
          // if (newValue?.service_name) {
          //   this.serviceName = newValue.service_name
          //   this.getColV2()
          //   this.getList()
          // }
        }
      }
    },
    props: {
      // 主表数据
      mainData: {
        type: Object
      },
      mainTable: {
        type: String
      },
      childService: {
        type: Object
      },
      appName: {
        type: String
      },
      list: {
        type: Array
      },
      config: {
        type: Object
      },
      // 字段:标签
      labels: {
        type: Object
      },
      type: {
        type: String,
        default: 'detaillist'
      },
      disabled: {
        type: Boolean,
        default: false
      }
    },
  }
</script>


<style lang="scss">
  .no-data {
    margin: 0 20rpx;
    padding: 20rpx 10rpx;
    color: #ADAEBB;
    text-align: center;
    background-color: #fff;
    border-radius: 0 0 20rpx 20rpx;
  }

  .handler-bar {
    display: flex;
    padding: 0 20rpx;
    width: 100%;

    .title {
      flex: 1;
      font-weight: 600;
    }

    .handler {
      display: flex;
      flex-wrap: wrap;
      max-width: 50%;

      .cu-btn {
        margin-left: 10rpx;
      }
    }
  }

  .cu-dialog {
    margin: 0 auto;

    .button-box {
      padding: 20rpx;

      .cu-btn {
        width: 40%;
        margin-right: 20rpx;
      }
    }
  }

  .cu-modal.show {
    text-align: center;
  }

  .child-form-wrap {
    max-height: 60vh;
    overflow-y: scroll;
  }

  .modal-content {
    padding: 20rpx;

    .title-bar {
      display: flex;
      justify-content: space-between;
      font-weight: 600;
      align-items: center;

      .title {
        padding: 20rpx;
      }
    }


    .button-box {
      text-align: center;

      .cu-btn {
        margin-right: 20rpx;
      }
    }
  }
</style>
